import { Box3Get, Box3Put, escapeHtml, nGet, prodUrl } from "@ap/util/request";
import * as vscode from "vscode";
import {
  showErrorMessage,
  showInformationMessage,
  showProgress,
} from "@ap/util/vscode/message";
import { auth } from "@ap/util/request";
import { updatePackageJson, getPackageJson } from "@ap/util/packageJson";
import { arenaErrorMsg } from "@ap/util/vscode/errorMsg";
import { CommandId, modelsMap } from "@ap/command";
import insertCode from "@ap/util/vscode/insertCode";
import { PackageConfig } from "@ap/types/config";
import openInternetImage from "@ap/webView/img";
import { off } from "process";
import { transformDao3Resources } from "./transformDao3Resources";

/**
 * 物品接口，扩展了共享的物品属性，添加了描述和ID。
 */
interface Item {
  animated: any;
  modelName: string;
  describe: string;
  modelId: number;
  modelDescription: string;
  modelPreviewUrl: string;
}

export interface ExtendedQuickPickItem extends vscode.QuickPickItem {
  animated: boolean;
  view: string;
}

// 当前模型总数
export let getModelCount: number;

// 当前模型配置数据
export let getModelConfig = {
  offset: 0,
  orderBy: 2,
};

/**
 * 异步获取扩展地图列表数组。
 * @returns 返回承诺，解析为数据项数组。
 */
export async function getBox3MapModelList(): Promise<
  ExtendedQuickPickItem[] | undefined
> {
  return getPackageJson<PackageConfig>("map").then(async (packageJson) => {
    if (packageJson) {
      const mapId = packageJson.id;
      if (mapId) {
        const requestOptions = {
          url:
            "models/v2?modelType=2&creativeMode=1&mapId=" +
            mapId +
            "&limit=50&orderBy=" +
            getModelConfig.orderBy +
            "&containerMode=edit&offset=" +
            getModelConfig.offset,
        };

        /**
         * 发送请求并等待响应。
         */
        const response = await Box3Get(requestOptions, "地图模型");
        /**
         * 检查响应是否成功，如果不成功则返回错误消息。
         */
        if (!response || response.code !== 200) {
          showErrorMessage(`获取地图模型失败: ${response?.code}`);
          return;
        }
        /**+
         * 处理响应数据，映射物品到数据项格式，并转义HTML字符以防止XSS攻击。
         */
        const dataSource: ExtendedQuickPickItem[] = response.data.rows.map(
          (item: Item) => ({
            label: `${escapeHtml(item.modelName)}`,
            description: item.modelId.toString(),
            detail: `${escapeHtml(item.modelDescription)}`,
            view: item.modelPreviewUrl,
            animated: item.animated,
          }),
        );
        getModelCount = response.data.count;
        let pageCount = getModelConfig.offset + 1;
        modelsMap.description = `第${pageCount}-${getModelConfig.offset + 50}项 | 共${getModelCount}项`;
        return dataSource;
      }
    }
  });
}

// 用于处理重命名模型的操作
export async function renameModel(
  packageJsonPath: string,
  modal: ExtendedQuickPickItem,
): Promise<void> {
  try {
    // 获取 package.json 文件内容
    const packageJson = await getPackageJson<PackageConfig>(packageJsonPath);

    if (packageJson) {
      // 显示输入框
      const userInput = await vscode.window.showInputBox({
        prompt: "重命名模型名称",
        value: modal.label,
        ignoreFocusOut: false,
      });

      if (userInput) {
        const requestOptions = {
          url: `model/project-shared/rename?mapId=${packageJson.id}&modelId=${modal.description}&modelName=${encodeURIComponent(userInput)}`,
        };

        // 发送请求并等待响应
        const response = await Box3Put(requestOptions, "地图模型重命名");

        // 检查响应是否成功
        if (!response || response.code !== 200) {
          showErrorMessage(`重命名模型失败: ${response?.msg}`);
          return;
        }

        // 刷新树形视图
        vscode.commands.executeCommand(CommandId.map_treeDataMapModelsRefresh);
      }
    }
  } catch (error) {
    showErrorMessage("重命名模型时发生错误");
    console.error(error);
  }
}
